import type { FC } from 'react';
import { useEffect } from 'react';
import { useSafeState, useMemoizedFn } from "ahooks";
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import '@wangeditor/editor/dist/css/style.css';
import styles from './styles.module.less';

type ProEditorProps = {
  value?: string;
  height?: number;
  onChange?: (value: string) => void;
}

const ProEditor: FC<ProEditorProps> = (props) => {
  const { value, height } = props;
  const [editor, setEditor] = useSafeState<IDomEditor|null>(null);

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
  }

  const handleChange = useMemoizedFn(
    (editor: IDomEditor) => {
      const html = editor.getHtml();
      props.onChange?.(html);
    }
  );

  const handleDestroy = useMemoizedFn(() => {
    return () => editor?.destroy?.();
  });

  useEffect(handleDestroy, [handleDestroy]);

  return (
    <div className={styles.wrapper}>
      <Toolbar
        editor={editor}
        mode="default"
        className={styles.toolbar}
        defaultConfig={toolbarConfig}
      />
      <Editor
        value={value}
        mode="default"
        onCreated={setEditor}
        onChange={handleChange}
        defaultConfig={editorConfig}
        style={{ height: height }}
      />
    </div>
  )
}

ProEditor.defaultProps = {
  height: 300
}

export default ProEditor;